package client

import (
	"context"
	"runtime"
	"sync"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	redis "github.com/go-redis/redis/v7"
	log "github.com/sirupsen/logrus"
	v1 "qabx.net/common/types/v1"
)

func NewRedisConnectionWithParams(url string, poolSize int, db int, password string) *v1.RedisConnection {
	//docker run -ti --rm -p 6379:6379 redis redis-server --requirepass cxx
	redisClient := &v1.RedisConnection{}
	redisClient.Client = redis.NewClient(&redis.Options{
		Addr:        url,
		IdleTimeout: time.Second * 120,
		Password:    password,
		DB:          db,
		PoolSize:    5 * runtime.NumCPU(),
		PoolTimeout: time.Second * 120,
		MaxRetries:  10,
	})

	if redisClient.Client == nil {
		return nil
	}
	redisClient.Mutex = &sync.Mutex{}

	return redisClient
}

func NewRedisClusterConnectionWithParams(urls []string, poolSize int, password string) *v1.RedisClusterConnection {
	//docker run -ti --rm -p 6379:6379 redis redis-server --requirepass cxx
	redisClient := &v1.RedisClusterConnection{}
	redisClient.Client = redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:        urls,
		IdleTimeout:  time.Second * 120,
		Password:     password,
		PoolSize:     5 * runtime.NumCPU(),
		PoolTimeout:  time.Second * 120,
		WriteTimeout: time.Second * 3,
		ReadTimeout:  time.Second * 3,
		MaxRetries:   10,
	})

	if redisClient.Client == nil {
		return nil
	}
	redisClient.Mutex = &sync.Mutex{}

	return redisClient
}

func NewRedisConnectionByDefault() *v1.RedisConnection {
	redisClient := NewRedisConnectionWithParams("0.0.0.0:6379", 10, 0, "")
	if redisClient == nil {
		log.Errorf("init redis connection failed")
		return nil
	}

	return redisClient
}

//func NewLogConnectionByDefault() *v1.SysLog {
//	return NewLogConnectionWithParams("0.0.0.0:514", "tcp", 0, "")
//}
//
//func NewLogConnectionWithParams(url string, proto string, priority syslog.Priority, appName string) *v1.SysLog {
//	//docker run -d -p 514:514 --rm rsyslog/syslog_appliance_alpine
//	sl := v1.SysLog{
//		Proto: proto,
//		// URL:   "172.24.119.72:5003",
//		URL: url,
//		// URL:            "114.255.112.69:5003",
//		Priority:       priority,
//		AppName:        appName,
//		MaxParallelism: 1000,
//	}
//	if err := sl.Run(); err != nil {
//		log.Errorf("init syslog failed: %v", err)
//		return nil
//	}
//	log.Infof("init syslog connection finished")
//	return &sl
//}

func NewMangoDBConnectionWithParams(url string) *mongo.Client {
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(url))
	if err != nil {
		log.Errorf("new mangodb connection faild")
		return nil
	}
	log.Infof("init mongodb connection finished")
	return client
}

func NewMangoDBConnectionDefault() *mongo.Client {
	return NewMangoDBConnectionWithParams("mongodb://root:cxx@0.0.0.0:27017")
}

func CloseMangoDBConnection(client *mongo.Client) {
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	client.Disconnect(ctx)
}
